package com.example.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程顺序执行！A执行完执行B，B执行完C，C执行完执行A
 * Condition 监视器
 * @author user
 *
 */
public class ProductConsumeLock3 {

	public static void main(String[] args) {
		Data4 data = new Data4();
		new Thread(()->{
			for(int i =0; i< 10;i++) {
				try {
					data.printA();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		},"A").start();
		
		new Thread(()->{
			for(int i =0; i< 10;i++) {
				try {
					data.printB();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		},"B").start();
		
		new Thread(()->{
			for(int i =0; i< 10;i++) {
				try {
					data.printC();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		},"C").start();
		
		
		
		
	}

}

// 资源类 OOP
class Data4 {
	// 属性、方法
	private int number = 1;
	Lock lock = new ReentrantLock();
	Condition condition1 = lock.newCondition();
	Condition condition2= lock.newCondition();
	Condition condition3 = lock.newCondition();
	// A线程
	public void printA() throws InterruptedException {
		lock.lock();
		try {
			// 业务代码，判断->执行-->通知
			while(number !=1) {
				// 等待
				condition1.await();
			}
			number = 2;
			System.out.println(Thread.currentThread().getName()+ ":"+ "AAAAAA");
			// 通知其他线程，我完毕了
			condition2.signal();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		
	}
	// B线程
	public void printB() throws InterruptedException {
		lock.lock();
		try {
			// 业务代码
			while(number != 2) {
				// 等待
				condition2.await();
			}
			number = 3;
			System.out.println(Thread.currentThread().getName()+ ":"+ "BBBBBB");
			// 通知其他线程，我完毕了
			condition3.signalAll();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
	
	// B线程
		public void printC() throws InterruptedException {
			lock.lock();
			try {
				// 业务代码
				while(number != 3) {
					// 等待
					condition3.await();
				}
				number = 1;
				System.out.println(Thread.currentThread().getName()+ ":"+ "CCCCCC");
				// 通知其他线程，我完毕了
				condition1.signalAll();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		}
	
}